// RAG智能问答系统 - 前端交互脚本

// ==================== 全局配置 ====================
const API_BASE_URL = '';  // 同域名，无需指定

// ==================== DOM元素 ====================
const elements = {
    // 系统状态
    statusDot: document.getElementById('statusDot'),
    systemStatus: document.getElementById('systemStatus'),
    refreshBtn: document.getElementById('refreshBtn'),
    modelName: document.getElementById('modelName'),
    docCount: document.getElementById('docCount'),
    dbPath: document.getElementById('dbPath'),
    
    // 选项卡
    tabBtns: document.querySelectorAll('.tab-btn'),
    tabPanes: document.querySelectorAll('.tab-pane'),
    
    // 单问题问答
    singleQuestion: document.getElementById('singleQuestion'),
    askBtn: document.getElementById('askBtn'),
    singleResult: document.getElementById('singleResult'),
    singleDocCount: document.getElementById('singleDocCount'),
    singleSources: document.getElementById('singleSources'),
    singleAnswer: document.getElementById('singleAnswer'),
    clearSingleBtn: document.getElementById('clearSingleBtn'),
    
    // 自定义参数问答
    maxDocs: document.getElementById('maxDocs'),
    scoreThreshold: document.getElementById('scoreThreshold'),
    customQuestion: document.getElementById('customQuestion'),
    customAskBtn: document.getElementById('customAskBtn'),
    customResult: document.getElementById('customResult'),
    customDocCount: document.getElementById('customDocCount'),
    customMaxDocs: document.getElementById('customMaxDocs'),
    customThreshold: document.getElementById('customThreshold'),
    customSources: document.getElementById('customSources'),
    customAnswer: document.getElementById('customAnswer'),
    clearCustomBtn: document.getElementById('clearCustomBtn'),
    
    // 加载和通知
    loadingOverlay: document.getElementById('loadingOverlay'),
    toast: document.getElementById('toast')
};

// ==================== 工具函数 ====================

/**
 * 显示加载状态
 */
function showLoading() {
    elements.loadingOverlay.classList.add('show');
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    elements.loadingOverlay.classList.remove('show');
}

/**
 * 显示Toast通知
 * @param {string} message - 消息内容
 * @param {string} type - 类型: success, error, warning, info
 */
function showToast(message, type = 'info') {
    const toast = elements.toast;
    toast.textContent = message;
    toast.className = `toast show ${type}`;
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

/**
 * API请求封装
 * @param {string} endpoint - API端点
 * @param {object} options - 请求选项
 * @returns {Promise} - 返回Promise
 */
async function apiRequest(endpoint, options = {}) {
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.error || '请求失败');
        }
        
        return data;
    } catch (error) {
        console.error('API请求失败:', error);
        throw error;
    }
}

/**
 * 更新系统状态
 */
async function updateSystemStatus() {
    try {
        const status = await apiRequest('/api/status');
        
        if (status.initialized) {
            elements.statusDot.className = 'status-dot ready';
            elements.systemStatus.textContent = '系统就绪';
            elements.modelName.textContent = status.model_name || '-';
            elements.docCount.textContent = status.document_count || '0';
            elements.dbPath.textContent = status.vector_db_path || '-';
        } else {
            elements.statusDot.className = 'status-dot error';
            elements.systemStatus.textContent = '系统未初始化';
            elements.modelName.textContent = '-';
            elements.docCount.textContent = '-';
            elements.dbPath.textContent = '-';
            
            // 尝试初始化
            const initResult = await apiRequest('/api/initialize', { method: 'POST' });
            if (initResult.success) {
                showToast('系统初始化成功', 'success');
                // 重新获取状态
                setTimeout(updateSystemStatus, 1000);
            }
        }
    } catch (error) {
        console.error('获取系统状态失败:', error);
        elements.statusDot.className = 'status-dot error';
        elements.systemStatus.textContent = '连接失败';
        showToast('无法连接到服务器', 'error');
    }
}

/**
 * 渲染Markdown内容
 * @param {string} markdown - Markdown文本
 * @returns {string} - 渲染后的HTML
 */
function renderMarkdown(markdown) {
    if (typeof marked !== 'undefined') {
        // 配置marked选项
        marked.setOptions({
            breaks: true,  // 支持换行符转换为<br>
            gfm: true,     // 启用GitHub风格的Markdown
            headerIds: false,
            mangle: false
        });
        return marked.parse(markdown);
    }
    // 如果marked未加载，降级为纯文本并保留换行
    return markdown.replace(/\n/g, '<br>');
}

/**
 * 渲染来源信息
 * @param {Array} sources - 来源列表
 * @param {HTMLElement} container - 容器元素
 */
function renderSources(sources, container) {
    if (!sources || sources.length === 0) {
        container.innerHTML = '';
        return;
    }
    
    const html = `
        <div class="sources-title">
            <i class="fas fa-book"></i>
            参考来源
        </div>
        ${sources.slice(0, 3).map((source, index) => `
            <div class="source-item">
                <i class="fas fa-file-alt"></i>
                <span class="source-name">${source.file}</span>
                <span class="source-score">相似度: ${source.similarity.toFixed(1)}%</span>
            </div>
        `).join('')}
    `;
    
    container.innerHTML = html;
}

// ==================== 选项卡切换 ====================
elements.tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const targetTab = btn.dataset.tab;
        
        // 更新按钮状态
        elements.tabBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        
        // 更新内容显示
        elements.tabPanes.forEach(pane => {
            if (pane.id === targetTab) {
                pane.classList.add('active');
            } else {
                pane.classList.remove('active');
            }
        });
    });
});

// ==================== 单问题问答 ====================
elements.askBtn.addEventListener('click', async () => {
    const question = elements.singleQuestion.value.trim();
    
    if (!question) {
        showToast('请输入问题', 'warning');
        return;
    }
    
    showLoading();
    
    try {
        const result = await apiRequest('/api/ask', {
            method: 'POST',
            body: JSON.stringify({ question })
        });
        
        if (result.success) {
            // 显示结果
            elements.singleResult.style.display = 'block';
            elements.singleDocCount.textContent = result.retrieved_docs;
            elements.singleAnswer.innerHTML = renderMarkdown(result.answer);
            
            // 渲染来源
            renderSources(result.sources, elements.singleSources);
            
            // 滚动到结果区域
            elements.singleResult.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            
            showToast('回答生成成功', 'success');
        } else {
            showToast(result.error || '获取回答失败', 'error');
        }
    } catch (error) {
        showToast(error.message || '请求失败', 'error');
    } finally {
        hideLoading();
    }
});

// 清除单问题结果
elements.clearSingleBtn.addEventListener('click', () => {
    elements.singleResult.style.display = 'none';
    elements.singleQuestion.value = '';
});

// ==================== 自定义参数问答 ====================
elements.customAskBtn.addEventListener('click', async () => {
    const question = elements.customQuestion.value.trim();
    const maxDocs = parseInt(elements.maxDocs.value);
    const scoreThreshold = parseFloat(elements.scoreThreshold.value);
    
    if (!question) {
        showToast('请输入问题', 'warning');
        return;
    }
    
    if (maxDocs < 1 || maxDocs > 20) {
        showToast('最大检索文档数应在1-20之间', 'warning');
        return;
    }
    
    if (scoreThreshold < 0 || scoreThreshold > 2.0) {
        showToast('距离阈值应在0.0-2.0之间（推荐0.5-1.5，值越小越严格）', 'warning');
        return;
    }
    
    showLoading();
    
    try {
        const result = await apiRequest('/api/ask', {
            method: 'POST',
            body: JSON.stringify({
                question,
                max_docs: maxDocs,
                score_threshold: scoreThreshold
            })
        });
        
        if (result.success) {
            // 显示结果
            elements.customResult.style.display = 'block';
            elements.customDocCount.textContent = result.retrieved_docs;
            elements.customMaxDocs.textContent = maxDocs;
            elements.customThreshold.textContent = scoreThreshold;
            elements.customAnswer.innerHTML = renderMarkdown(result.answer);
            
            // 渲染来源
            renderSources(result.sources, elements.customSources);
            
            // 滚动到结果区域
            elements.customResult.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            
            showToast('回答生成成功', 'success');
        } else {
            showToast(result.error || '获取回答失败', 'error');
        }
    } catch (error) {
        showToast(error.message || '请求失败', 'error');
    } finally {
        hideLoading();
    }
});

// 清除自定义参数问答结果
elements.clearCustomBtn.addEventListener('click', () => {
    elements.customResult.style.display = 'none';
    elements.customQuestion.value = '';
});

// ==================== 刷新状态 ====================
elements.refreshBtn.addEventListener('click', () => {
    updateSystemStatus();
    showToast('状态已刷新', 'info');
});

// ==================== 页面加载完成 ====================
window.addEventListener('DOMContentLoaded', () => {
    console.log('RAG智能问答系统前端已加载');
    
    // 获取初始状态
    updateSystemStatus();
    
    // 定期更新状态（每30秒）
    setInterval(updateSystemStatus, 30000);
});

// ==================== 键盘快捷键 ====================
document.addEventListener('keydown', (e) => {
    // Ctrl + Enter 提交问题
    if (e.ctrlKey && e.key === 'Enter') {
        const activeTab = document.querySelector('.tab-pane.active');
        if (activeTab) {
            if (activeTab.id === 'single') {
                elements.askBtn.click();
            } else if (activeTab.id === 'custom') {
                elements.customAskBtn.click();
            }
        }
    }
});



